from odoo import models, fields, api, _
from odoo.exceptions import UserError, ValidationError


# 审批流模板类
class WorkflowTemplate(models.Model):
    _name = 'sb.workflow.template'
    _description = 'Approval Workflow Template Class'

    name = fields.Char(string="Name", translate=True)
    workflow_type = fields.Selection([
        ('account_in', 'purchase invoice'),
        ('other', 'Other')
    ], string="Approval Category")
    active = fields.Boolean(default=True)
    # Template approval item ids
    sb_workflow_template_item_ids = fields.One2many('sb.workflow.template.item', 'sb_workflow_template_id',
                                                    string='Template Approval Items')
    code = fields.Char(string='code')

    def get_value_and_label(self, field_name, record):
        field_info = record._fields.get(field_name)
        label = field_info.string if field_info.string else field_name
        value = getattr(record, field_name, False)

        if field_info:
            if field_info.type == 'selection' and value is not False:
                selection_dict = dict(field_info.selection)
                value = selection_dict.get(value, value)
            elif field_info.type == 'many2one' and value:
                value = value.display_name
            elif field_name == 'need_update_pn':
                value = 'True' if value else 'False'

        return {'label': label, 'value': value if value is not False else ''}


# 工作流模板-审核项
class WorkflowTemplateItem(models.Model):
    _name = 'sb.workflow.template.item'
    _description = 'Approval Workflow Template - Approval Item'
    _order = 'audit_level asc'

    name = fields.Char(string="Name", translate=True)
    user_group_ids = fields.Many2many('res.users', string="Approvers")

    # Approval Level
    audit_level = fields.Integer(default=1, string="Approval Level")

    # 工作流模板
    sb_workflow_template_id = fields.Many2one('sb.workflow.template', ondelete="cascade")
    is_plan = fields.Boolean(string='Plan or not', default=False)
